<template>
  <div>
    <div class="input-section">
      <div class="right">
        <el-input
          v-model="searchQuery"
          placeholder="请输入公告名"
          style="
            width: 500px;
            height: 40px;
            margin-bottom: 20px;
            margin-top: 20px;
          "
          :prefix-icon="Search"
          clearable
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="button-group">
        <el-button @click="exportToExcel" type="success">导出 Excel</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button
          type="danger"
          @click="handleBatchDelete"
          :disabled="selectedRows.length === 0"
        >
          批量删除
        </el-button>
      </div>
    </div>
    <el-table
      ref="tableRef"
      :data="tableData"
      style="width: 100%"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column prop="id" label="社团公告id" width="70" />
      <el-table-column prop="clubName" label="所属社团" width="100" />
      <el-table-column prop="title" label="公告标题" width="200" />
      <el-table-column prop="content" label="公告内容" width="400" />
      <el-table-column
        prop="createTime"
        label="公告创建时间"
        sortable
        width="150"
      />
      <el-table-column
        prop="isDelete"
        label="是否删除"
        width="100"
        :filters="deleteFilters"
        :filter-method="filterResult"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag v-if="row.isDelete === 0" type="success">正常</el-tag>
          <el-tag v-else-if="row.isDelete === 1" type="warning">已删除</el-tag>
          <el-tag v-else type="danger">未知类型</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row, $index }">
          <el-button size="small" @click="handleEdit(row)" type="primary"
            >编辑</el-button
          >
          <el-popconfirm title="确认删除吗？" @confirm="handleDelete($index)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-section">
      <div class="record-count">共查询到 {{ total }} 条记录</div>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        v-model:page-size="pageSize"
        v-model:current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        @current-change="loadTableData"
        @size-change="loadTableData"
      />
    </div>
    <!--新增社团公告对话框-->
    <el-dialog v-model="addDialogVisible" title="新增社团公告" width="600px">
      <el-form :model="addForm" label-width="100px">
        <el-form-item label="社团ID" prop="clubId" required>
          <el-input-number
            v-model="addForm.clubId"
            :min="1"
            placeholder="请输入社团ID"
          />
        </el-form-item>

        <el-form-item label="公告标题" prop="title" required>
          <el-input v-model="addForm.title" placeholder="请输入公告标题" />
        </el-form-item>

        <el-form-item label="公告内容" prop="content" required>
          <el-input
            v-model="addForm.content"
            type="textarea"
            :rows="5"
            placeholder="请输入公告内容"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitAddAnnouncement"
          :loading="submitLoading"
        >
          提交
        </el-button>
      </template>
    </el-dialog>
    <!-- 编辑公告对话框 -->
    <el-dialog
      v-model="announcementDialogVisible"
      title="编辑社团公告"
      width="600px"
    >
      <el-form :model="announcementForm" label-width="100px">
        <el-form-item label="公告标题" prop="title">
          <el-input
            v-model="announcementForm.title"
            placeholder="请输入公告标题"
          />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input
            type="textarea"
            v-model="announcementForm.content"
            placeholder="请输入公告内容"
            :rows="5"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="announcementDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateAnnouncement">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import { getNoticeAllAPI } from "@/apis/notice";
import { deleteNoticeAPI } from "@/apis/notice";
import { addAnnouncementAPI, updateAnnouncementAPI } from "@/apis/notice";
import * as XLSX from "xlsx";
// 导出为 Excel
const exportToExcel = () => {
  if (!tableData.value.length) {
    ElMessage.warning("没有可导出的数据");
    return;
  }
  console.log("表格数据：", tableData.value);
  // 提取你想要导出的字段
  const exportData = tableData.value.map((item) => ({
    社团公告ID: item.id,
    社团名称: item.clubName,
    公告标题: item.title,
    公告内容: item.content,
  }));

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "社团信息");

  // 下载 Excel 文件
  XLSX.writeFile(
    workbook,
    `社团列表_${new Date().toISOString().slice(0, 10)}.xlsx`
  );
};
interface Notice {
  id: number;
  clubName: string;
  title: string;
  content: string;
  createTime: string;
  isDelete: boolean;
}

const tableRef = ref<any>();
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(8);
const selectedRows = ref<Notice[]>([]); // 存储选中的行数据
const total = ref(0); // 总记录数
//加载表格数据
const tableData = ref<Notice[]>([]);

const loadTableData = async () => {
  try {
    const response = await getNoticeAllAPI(
      currentPage.value,
      pageSize.value,
      searchQuery.value
    );
    console.log("接口返回数据:", response);

    if (
      response.code === 0 &&
      response.data &&
      Array.isArray(response.data.records)
    ) {
      tableData.value = response.data.records.map((record) => ({
        id: record.id,
        clubName: record.clubName || 0,
        title: record.title || "-",
        content: record.content || "-",
        createTime: record.createTime || "-",
        isDelete: record.isDelete || 0,
        clubId: record.clubId,
      }));
      total.value = response.data.total || 0; // 设置总记录数
    } else {
      tableData.value = [];
      total.value = 0;
      ElMessage.warning("未找到用户申请数据");
    }
  } catch (error) {
    console.error("加载用户申请列表失败:", error);
    tableData.value = [];
    total.value = 0;
    ElMessage.error("加载用户申请列表失败，请稍后重试");
  }
};

// 搜索功能（
const handleSearch = async () => {
  currentPage.value = 1; // 搜索时重置到第一页
  try {
    await loadTableData();
  } catch (error) {
    console.error("搜索失败:", error);
    ElMessage.error("搜索失败，请稍后重试");
  }
};
onMounted(() => {
  loadTableData(); 
});
const resetSearch = () => {
  searchQuery.value = ""; 
  loadTableData(); 
};

const deleteFilters = [
  { text: "正常", value: 0 },
  { text: "已删除", value: 1 },
];

// 删除公告（优化版）
const handleDelete = async (index: number) => {
  try {
    const notice = tableData.value[index];
    if (!notice?.id) {
      ElMessage.warning("未找到要删除的公告");
      return;
    }

    await ElMessageBox.confirm("确定要删除此公告吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const loading = ElLoading.service({
      lock: true,
      text: "删除中...",
    });

    const response = await deleteNoticeAPI(notice.id);
    loading.close();

    if (response.code === 0) {
      ElMessage.success("删除成功");
      await loadTableData(); // 等待数据刷新完成
    } else {
      throw new Error(response.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      // 忽略用户取消操作
      console.error("删除失败:", error);
      ElMessage.error(error.message || "删除失败");
      await loadTableData(); // 出错时也刷新数据
    }
  }
};

// 批量删除（优化版）
const handleBatchDelete = async () => {
  try {
    if (selectedRows.value.length === 0) {
      return ElMessage.warning("请至少选择一条记录");
    }

    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条公告吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const loading = ElLoading.service({
      lock: true,
      text: "批量删除中...",
    });

    const ids = selectedRows.value.map((item) => item.id);
    const response = await deleteNoticeAPI(ids);
    loading.close();

    if (response.code === 0) {
      ElMessage.success(`成功删除 ${ids.length} 条公告`);
      selectedRows.value = [];
      await loadTableData();
    } else {
      throw new Error(response.message || "批量删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除失败:", error);
      ElMessage.error(error.message || "批量删除失败");
      await loadTableData();
    }
  }
};

const announcementDialogVisible = ref(false);
const announcementForm = ref({
  id: 0,
  clubId: 0,
  title: "",
  content: "",
  createTime: "",
  isDelete: 0,
});
// 1. 修改handleEdit方法
const handleEdit = (row: any) => {
  announcementForm.value = {
    id: row.id,
    clubId: row.clubId ?? null, 
    title: row.title,
    content: row.content,
    createTime: row.createTime,
    isDelete: row.isDelete ? 1 : 0,
  };
  announcementDialogVisible.value = true;
};

// 2. 修改updateAnnouncement方法
const updateAnnouncement = async () => {
  try {
    const { id, clubId, title, content, createTime, isDelete } =
      announcementForm.value;

    if (!title || !content) {
      ElMessage.warning("请填写完整的公告信息");
      return;
    }

    // 确保使用原有的clubId，不修改社团关联
    const response = await updateAnnouncementAPI(
      id,
      createTime,
      isDelete,
      clubId, 
      title, 
      content 
    );

    if (response.code === 0) {
      ElMessage.success("公告更新成功");
      announcementDialogVisible.value = false;
      loadTableData();
    } else {
      throw new Error(response.message || "更新失败");
    }
  } catch (error) {
    console.error("更新失败:", error);
    ElMessage.error("更新失败: " + error.message);
  }
};

// 新增公告相关状态
const addDialogVisible = ref(false);
const submitLoading = ref(false);
const addForm = ref({
  clubId: null as number | null,
  title: "",
  content: "",
});

// 打开新增弹窗
const handleAdd = () => {
  addForm.value = {
    clubId: null,
    title: "",
    content: "",
  };
  addDialogVisible.value = true;
};

// 提交新增公告
const submitAddAnnouncement = async () => {
  try {
    // 表单验证
    if (!addForm.value.clubId) {
      return ElMessage.warning("请输入社团ID");
    }
    if (!addForm.value.title.trim()) {
      return ElMessage.warning("请输入公告标题");
    }
    if (!addForm.value.content.trim()) {
      return ElMessage.warning("请输入公告内容");
    }

    submitLoading.value = true;

    const response = await addAnnouncementAPI(
      addForm.value.clubId,
      addForm.value.title,
      addForm.value.content
    );

    if (response.code === 0) {
      ElMessage.success("公告发布成功");
      addDialogVisible.value = false;
      await loadTableData(); // 刷新公告列表
    } else {
      throw new Error(response.message || "发布失败");
    }
  } catch (error) {
    console.error("发布公告失败:", error);
    ElMessage.error(error.message || "发布公告失败");
  } finally {
    submitLoading.value = false;
  }
};

const handleSelectionChange = (selection: Notice[]) => {
  selectedRows.value = selection;
};
</script>

<style scoped>
.input-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 10px;
}

.el-table {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-count {
  margin-left: 10px;
}

.el-pagination {
  justify-content: flex-end;
}
.right {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
